import {
  login,
  getInfo,
  updateMember,
  sendCode,
  register,
  passwordUpdate,
  authMemberInfo,
  passwordForget,
  getPlatInfo
} from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import router, { resetRouter } from "@/router";
import { messageCountUnread } from "@/api/system";

const state = {
  token: getToken(),
  name: "",
  avatar: "",
  introduction: "",
  roles: [],
  userInfo: "",
  ICBCInfo:'',
  typeJson: [
    { value: 2, label: "供应商(服务商)" },
    { value: 1, label: "采购商" },
    // { value: 0, label: '超级管理员' },
    // { value: 99, label: '普通管理员' }
  ],
  authTypeJson: [
    { value: 1, label: "企业" },
    { value: 2, label: "个人" }
  ],
  companyTypeJson: [
    { value: 1, label: "兰炭企业" },
    { value: 0, label: "非兰炭企业" }
  ],
  messageCount: 0
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo;
  },
  SET_messageCount: (state, userInfo) => {
    state.messageCount = userInfo;
  },
  SET_ICBCInfo: (state, ICBCInfo) => {
    state.ICBCInfo = ICBCInfo;
  }
};

const actions = {
  // 获取站内信未读数量
  getMessageCount({ commit }, params) {
    messageCountUnread(params).then(response => {
      commit("SET_messageCount", response);
    });
  },
  // 注册
  register({ commit }, params) {
    return new Promise((resolve, reject) => {
      register(params)
        .then(response => {
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  // 获取验证码
  getCode({ commit }, params) {
    return new Promise((resolve, reject) => {
      sendCode(params)
        .then(response => {
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo)
        .then(response => {
          commit("SET_TOKEN", response);
          setToken(response);
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, dispatch }, Dontset) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then(res => {
          if (!Dontset) {
            const response = {
              roles: ["admin"],
              introduction: "I am a super administrator",
              avatar:
                res.companyLogo ||
                "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
              name: "Super Admin"
            };
            commit("SET_ROLES", response.roles);
            commit("SET_NAME", res.roleName);
            commit("SET_AVATAR", response.avatar);
            commit("SET_INTRODUCTION", response.introduction);
            commit("SET_USERINFO", res);
          }
          resolve(res);
        })
        .catch(error => {
          dispatch("user/logout", null, { root: true });
          reject(error);
        });
    });
  },
  
  // 获取工行信息
  getPlatInfo({commit,dispatch},Dontset){
    return new Promise((resolve, reject) => {
      getPlatInfo()
        .then(res => {
          commit("SET_ICBCInfo", res);
          resolve(res);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // update user info
  updateMember({ dispatch }, data) {
    return new Promise((resolve, reject) => {
      updateMember(data)
        .then(res => {
          dispatch("user/getInfo", null, { root: true });
          resolve(res);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  // update user info
  authMemberInfo({ dispatch }, data) {
    return new Promise((resolve, reject) => {
      authMemberInfo(data)
        .then(res => {
          dispatch("user/getInfo", null, { root: true });
          resolve(res);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // update user info
  passwordUpdate({ dispatch }, data) {
    return new Promise((resolve, reject) => {
      passwordUpdate(data)
        .then(res => {
          resolve(res);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  // update user info
  passwordForget({ dispatch }, data) {
    return new Promise((resolve, reject) => {
      passwordForget(data)
        .then(res => {
          resolve(res);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
      commit("SET_TOKEN", "");
      commit("SET_USERINFO", {});
      commit("SET_ROLES", []);
      removeToken();
      resetRouter();

      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch("tagsView/delAllViews", null, { root: true });

      resolve();
      // }).catch(error => {
      //   reject(error)
      // })
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit("SET_TOKEN", "");
      commit("SET_USERINFO", {});
      commit("SET_ROLES", []);
      // removeToken()
      resolve();
    });
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    await dispatch("user/getInfo");

    resetRouter();

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch(
      "permission/generateRoutes",
      ["admin"],
      { root: true }
    );
    // const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes);

    // reset visited views and cached views
    dispatch("tagsView/delAllViews", null, { root: true });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
